package com.lms.web.borrowRecordManagement;

import com.lms.mapper.BorrowRecordDAO;
import com.lms.pojo.BorrowRecord;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(
        name = "AddBorrowRecordServlet",
        value = "/addBorrowRecord"
)
public class AddBorrowRecordServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单提交的数据
        int userId = Integer.parseInt(request.getParameter("userId"));
        int bookId = Integer.parseInt(request.getParameter("bookId"));
        String borrowDate = request.getParameter("borrowDate");
        String returnDate = request.getParameter("returnDate");

        // 在此执行添加借阅记录的操作，例如将数据插入数据库
        BorrowRecordDAO dao = new BorrowRecordDAO();

        BorrowRecord borrowRecord = new BorrowRecord();
        borrowRecord.setUserID(userId);
        borrowRecord.setBookID(bookId);
        try {
            borrowRecord.setBorrowDate(stringToDate(borrowDate));
            borrowRecord.setReturnDate(stringToDate(returnDate));
        } catch (ParseException e) {
            e.printStackTrace();
            //格式错误
        }
        boolean isAdd = dao.add(borrowRecord);
        if (isAdd) {
            // 重定向到借阅记录列表页面
            response.sendRedirect("borrowRecord.jsp");
        } else {
            request.setAttribute("error", "添加借阅失败");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
        }


    }

    Date stringToDate(String str) throws ParseException {
        return new SimpleDateFormat("yyyy-MM-dd").parse(str);
    }
}
